import {
  BellOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  EyeOutlined,
  FilterOutlined,
  GlobalOutlined,
  HeartOutlined,
  InfoCircleOutlined,
  KeyOutlined,
  LockOutlined,
  MailOutlined,
  MoreOutlined,
  PhoneOutlined,
  PlusOutlined,
  ReloadOutlined,
  SaveOutlined,
  SearchOutlined,
  SecurityScanOutlined,
  SendOutlined,
  SettingOutlined,
  ShareAltOutlined,
  StarOutlined,
  TeamOutlined,
  UnlockOutlined,
  UploadOutlined,
  UserOutlined,
  WarningOutlined,
} from "@ant-design/icons";
import {
  ProCard,
  ProDescriptions,
  ProForm,
  ProFormSelect,
  ProFormText,
} from "@ant-design/pro-components";
import {
  Alert,
  AutoComplete,
  Avatar,
  Badge,
  Button,
  Calendar,
  Card,
  Carousel,
  Cascader,
  Checkbox,
  Col,
  Collapse,
  DatePicker,
  Descriptions,
  Divider,
  Drawer,
  Dropdown,
  Empty,
  Form,
  Image,
  Input,
  InputNumber,
  List,
  Mentions,
  Menu,
  Modal,
  Pagination,
  Popconfirm,
  Progress,
  Radio,
  Rate,
  Result,
  Row,
  Select,
  Skeleton,
  Slider,
  Space,
  Spin,
  Statistic,
  Steps,
  Switch,
  Table,
  Tabs,
  Tag,
  TimePicker,
  Timeline,
  Tooltip,
  Transfer,
  Tree,
  TreeSelect,
  Typography,
  Upload,
  message,
  notification,
} from "antd";
import type { MenuProps } from "antd";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";

import React, { useEffect, useState } from "react";

const { Title, Paragraph, Text } = Typography;
const { TabPane } = Tabs;
const { Panel } = Collapse;
const { Step } = Steps;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { Option } = Select;

interface UserItem {
  id: string;
  username: string;
  email: string;
  role: "admin" | "manager" | "user" | "guest";
  status: "active" | "inactive" | "locked";
  department: string;
  lastLogin: string;
  loginCount: number;
  avatar?: string;
  permissions: string[];
  phone: string;
  createTime: string;
}

interface PermissionItem {
  id: string;
  name: string;
  code: string;
  description: string;
  status: "enabled" | "disabled";
  category: string;
}

const Page30: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<UserItem[]>([]);
  const [permissions, setPermissions] = useState<PermissionItem[]>([]);
  const [selectedUser, setSelectedUser] = useState<UserItem | null>(null);
  const [selectedPermission, setSelectedPermission] =
    useState<PermissionItem | null>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [autoRefresh, setAutoRefresh] = useState(false);
  const [rating, setRating] = useState(4);
  const [sliderValue, setSliderValue] = useState(50);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchText, setSearchText] = useState("");
  const [activeTab, setActiveTab] = useState("1");

  useEffect(() => {
    // 模拟用户数据
    const mockUsers: UserItem[] = [
      {
        id: "1",
        username: "admin",
        email: "admin@company.com",
        role: "admin",
        status: "active",
        department: "技术部",
        lastLogin: "2024-01-20 10:30:00",
        loginCount: 156,
        permissions: ["user:read", "user:write", "user:delete", "system:admin"],
        phone: "13800138000",
        createTime: "2023-01-01",
      },
      {
        id: "2",
        username: "manager1",
        email: "manager1@company.com",
        role: "manager",
        status: "active",
        department: "产品部",
        lastLogin: "2024-01-19 15:20:00",
        loginCount: 89,
        permissions: ["user:read", "user:write"],
        phone: "13800138001",
        createTime: "2023-03-15",
      },
      {
        id: "3",
        username: "user1",
        email: "user1@company.com",
        role: "user",
        status: "active",
        department: "设计部",
        lastLogin: "2024-01-18 09:15:00",
        loginCount: 45,
        permissions: ["user:read"],
        phone: "13800138002",
        createTime: "2023-06-20",
      },
      {
        id: "4",
        username: "guest1",
        email: "guest1@company.com",
        role: "guest",
        status: "locked",
        department: "市场部",
        lastLogin: "2024-01-10 14:30:00",
        loginCount: 12,
        permissions: ["user:read"],
        phone: "13800138003",
        createTime: "2023-09-10",
      },
    ];
    setUsers(mockUsers);

    // 模拟权限数据
    const mockPermissions: PermissionItem[] = [
      {
        id: "1",
        name: "用户查看",
        code: "user:read",
        description: "查看用户信息",
        status: "enabled",
        category: "用户管理",
      },
      {
        id: "2",
        name: "用户编辑",
        code: "user:write",
        description: "编辑用户信息",
        status: "enabled",
        category: "用户管理",
      },
      {
        id: "3",
        name: "用户删除",
        code: "user:delete",
        description: "删除用户",
        status: "enabled",
        category: "用户管理",
      },
      {
        id: "4",
        name: "系统管理",
        code: "system:admin",
        description: "系统管理员权限",
        status: "enabled",
        category: "系统管理",
      },
    ];
    setPermissions(mockPermissions);
  }, []);

  // 点击事件处理函数
  const handleUserClick = (user: UserItem) => {
    setSelectedUser(user);
    setModalVisible(true);
  };

  const handlePermissionClick = (permission: PermissionItem) => {
    setSelectedPermission(permission);
    setPermissionModalVisible(true);
  };

  const handleStatusChange = (
    userId: string,
    newStatus: UserItem["status"],
  ) => {
    setUsers((prev) =>
      prev.map((user) =>
        user.id === userId ? { ...user, status: newStatus } : user,
      ),
    );
    message.success(`用户状态已更新为: ${newStatus}`);
  };

  const handleRoleChange = (userId: string, role: UserItem["role"]) => {
    setUsers((prev) =>
      prev.map((user) => (user.id === userId ? { ...user, role } : user)),
    );
    message.info(`用户角色已更新为: ${role}`);
  };

  const handleRefreshData = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success("数据刷新完成");
    }, 1000);
  };

  const handleExportData = () => {
    message.loading("正在导出数据...", 2).then(() => {
      message.success("数据导出成功！");
    });
  };

  const handleImportData = () => {
    message.info("点击了导入按钮");
  };

  const handleAddUser = () => {
    message.success("添加新用户");
  };

  const handleEditUser = (user: UserItem) => {
    message.info(`编辑用户: ${user.username}`);
    setDrawerVisible(true);
  };

  const handleDeleteUser = (user: UserItem) => {
    message.success(`删除用户: ${user.username}`);
    setUsers((prev) => prev.filter((u) => u.id !== user.id));
  };

  const handleLockUser = (user: UserItem) => {
    const newStatus = user.status === "locked" ? "active" : "locked";
    handleStatusChange(user.id, newStatus);
    message.success(`用户已${newStatus === "locked" ? "锁定" : "解锁"}`);
  };

  const handleResetPassword = (user: UserItem) => {
    message.success(`重置用户 ${user.username} 的密码`);
  };

  const handleSendMessage = (user: UserItem) => {
    message.info(`发送消息给用户: ${user.username}`);
  };

  const handleStepChange = (current: number) => {
    setCurrentStep(current);
    message.info(`切换到步骤: ${current + 1}`);
  };

  const handleRatingChange = (value: number) => {
    setRating(value);
    message.success(`评分已更新为: ${value} 星`);
  };

  const handleSliderChange = (value: number) => {
    setSliderValue(value);
    message.info(`滑块值: ${value}`);
  };

  const handleAutoRefreshChange = (checked: boolean) => {
    setAutoRefresh(checked);
    message.success(`自动刷新已${checked ? "开启" : "关闭"}`);
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    message.info(`切换到标签: ${key}`);
  };

  const handleTableSelectionChange = (selectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(selectedRowKeys);
    message.info(`选中了 ${selectedRowKeys.length} 个用户`);
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
    message.info(`搜索: ${value}`);
  };

  const getRoleColor = (role: UserItem["role"]) => {
    switch (role) {
      case "admin":
        return "red";
      case "manager":
        return "orange";
      case "user":
        return "blue";
      case "guest":
        return "green";
      default:
        return "default";
    }
  };

  const getStatusColor = (status: UserItem["status"]) => {
    switch (status) {
      case "active":
        return "green";
      case "inactive":
        return "orange";
      case "locked":
        return "red";
      default:
        return "default";
    }
  };

  const getRoleText = (role: UserItem["role"]) => {
    switch (role) {
      case "admin":
        return "管理员";
      case "manager":
        return "经理";
      case "user":
        return "用户";
      case "guest":
        return "访客";
      default:
        return role;
    }
  };

  const getStatusText = (status: UserItem["status"]) => {
    switch (status) {
      case "active":
        return "活跃";
      case "inactive":
        return "非活跃";
      case "locked":
        return "已锁定";
      default:
        return status;
    }
  };

  const getUserMenuItems = (user: UserItem): MenuProps["items"] => [
    {
      key: "edit",
      icon: <EditOutlined />,
      label: "编辑",
      onClick: () => handleEditUser(user),
    },
    {
      key: "lock",
      icon: user.status === "locked" ? <UnlockOutlined /> : <LockOutlined />,
      label: user.status === "locked" ? "解锁" : "锁定",
      onClick: () => handleLockUser(user),
    },
    {
      key: "resetPassword",
      icon: <KeyOutlined />,
      label: "重置密码",
      onClick: () => handleResetPassword(user),
    },
    {
      key: "message",
      icon: <MailOutlined />,
      label: "发送消息",
      onClick: () => handleSendMessage(user),
    },
    {
      type: "divider",
    },
    {
      key: "delete",
      icon: <DeleteOutlined />,
      label: "删除",
      danger: true,
      onClick: () => handleDeleteUser(user),
    },
  ];

  // 表格列定义
  const columns: ColumnsType<UserItem> = [
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
      render: (text, record) => (
        <Space>
          <Avatar icon={<UserOutlined />} />
          <a onClick={() => handleUserClick(record)}>{text}</a>
        </Space>
      ),
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
      render: (role) => (
        <Tag color={getRoleColor(role)}>{getRoleText(role)}</Tag>
      ),
      filters: [
        { text: "管理员", value: "admin" },
        { text: "经理", value: "manager" },
        { text: "用户", value: "user" },
        { text: "访客", value: "guest" },
      ],
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => (
        <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
      ),
    },
    {
      title: "部门",
      dataIndex: "department",
      key: "department",
    },
    {
      title: "最后登录",
      dataIndex: "lastLogin",
      key: "lastLogin",
      sorter: true,
    },
    {
      title: "登录次数",
      dataIndex: "loginCount",
      key: "loginCount",
      sorter: true,
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Dropdown
            menu={{ items: getUserMenuItems(record) }}
            trigger={["click"]}
          >
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Title level={2}>页面 30 - 用户权限管理系统</Title>

      {/* 顶部操作栏 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col span={18}>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAddUser}
            >
              新增用户
            </Button>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefreshData}
              loading={loading}
            >
              刷新
            </Button>
            <Button icon={<DownloadOutlined />} onClick={handleExportData}>
              导出
            </Button>
            <Button icon={<UploadOutlined />} onClick={handleImportData}>
              导入
            </Button>
            <Input.Search
              placeholder="搜索用户..."
              onSearch={handleSearch}
              style={{ width: 200 }}
            />
          </Space>
        </Col>
        <Col span={6} style={{ textAlign: "right" }}>
          <Space>
            <Text>自动刷新:</Text>
            <Switch checked={autoRefresh} onChange={handleAutoRefreshChange} />
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        {/* 统计卡片 */}
        <Col span={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={users.length}
              prefix={<Badge count={users.length} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃用户"
              value={users.filter((u) => u.status === "active").length}
              valueStyle={{ color: "#3f8600" }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="管理员"
              value={users.filter((u) => u.role === "admin").length}
              valueStyle={{ color: "#cf1322" }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日登录"
              value={
                users.filter((u) => u.lastLogin.includes("2024-01-20")).length
              }
              valueStyle={{ color: "#1890ff" }}
            />
          </Card>
        </Col>
      </Row>

      <Tabs
        activeKey={activeTab}
        onChange={handleTabChange}
        style={{ marginTop: 16 }}
      >
        <TabPane tab="用户管理" key="1">
          <ProCard>
            <Table
              columns={columns}
              dataSource={users}
              rowSelection={{
                selectedRowKeys,
                onChange: handleTableSelectionChange,
              }}
              pagination={{
                total: users.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
              }}
            />
          </ProCard>
        </TabPane>

        <TabPane tab="权限管理" key="2">
          <Row gutter={[16, 16]}>
            <Col span={12}>
              <ProCard title="权限列表">
                <List
                  dataSource={permissions}
                  renderItem={(permission) => (
                    <List.Item
                      actions={[
                        <Button
                          key="edit"
                          type="link"
                          onClick={() => handlePermissionClick(permission)}
                        >
                          编辑
                        </Button>,
                        <Switch
                          key="status"
                          checked={permission.status === "enabled"}
                          onChange={(checked) => {
                            setPermissions((prev) =>
                              prev.map((p) =>
                                p.id === permission.id
                                  ? {
                                      ...p,
                                      status: checked ? "enabled" : "disabled",
                                    }
                                  : p,
                              ),
                            );
                            message.success(
                              `权限 ${permission.name} 已${checked ? "启用" : "禁用"}`,
                            );
                          }}
                        />,
                      ]}
                    >
                      <List.Item.Meta
                        avatar={<Avatar icon={<SecurityScanOutlined />} />}
                        title={permission.name}
                        description={
                          <Space direction="vertical" size="small">
                            <Text type="secondary">
                              {permission.description}
                            </Text>
                            <Space>
                              <Tag color="blue">{permission.code}</Tag>
                              <Tag color="green">{permission.category}</Tag>
                            </Space>
                          </Space>
                        }
                      />
                    </List.Item>
                  )}
                />
              </ProCard>
            </Col>

            <Col span={12}>
              <ProCard title="权限分配">
                <Space direction="vertical" style={{ width: "100%" }}>
                  <div>
                    <Text>选择用户: </Text>
                    <Select
                      placeholder="请选择用户"
                      style={{ width: 200 }}
                      options={users.map((user) => ({
                        label: user.username,
                        value: user.id,
                      }))}
                    />
                  </div>
                  <div>
                    <Text>选择权限: </Text>
                    <Select
                      mode="multiple"
                      placeholder="请选择权限"
                      style={{ width: 300 }}
                      options={permissions.map((p) => ({
                        label: p.name,
                        value: p.code,
                      }))}
                    />
                  </div>
                  <Button
                    type="primary"
                    onClick={() => message.success("权限分配成功")}
                  >
                    分配权限
                  </Button>
                </Space>
              </ProCard>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="系统设置" key="3">
          <Row gutter={[16, 16]}>
            <Col span={8}>
              <ProCard title="安全设置">
                <Space direction="vertical" style={{ width: "100%" }}>
                  <div>
                    <Text>密码强度: </Text>
                    <Rate value={rating} onChange={handleRatingChange} />
                  </div>
                  <div>
                    <Text>会话超时: {sliderValue}分钟</Text>
                    <Slider value={sliderValue} onChange={handleSliderChange} />
                  </div>
                  <div>
                    <Text>双因素认证: </Text>
                    <Switch defaultChecked />
                  </div>
                  <div>
                    <Text>登录失败锁定: </Text>
                    <Switch defaultChecked />
                  </div>
                </Space>
              </ProCard>
            </Col>

            <Col span={8}>
              <ProCard title="通知设置">
                <Space direction="vertical" style={{ width: "100%" }}>
                  <Checkbox defaultChecked>邮件通知</Checkbox>
                  <Checkbox defaultChecked>短信通知</Checkbox>
                  <Checkbox>微信通知</Checkbox>
                  <Checkbox defaultChecked>系统通知</Checkbox>
                </Space>
              </ProCard>
            </Col>

            <Col span={8}>
              <ProCard title="系统信息">
                <Descriptions column={1} size="small">
                  <Descriptions.Item label="系统版本">v2.1.0</Descriptions.Item>
                  <Descriptions.Item label="数据库版本">
                    MySQL 8.0
                  </Descriptions.Item>
                  <Descriptions.Item label="服务器状态">正常</Descriptions.Item>
                  <Descriptions.Item label="最后更新">
                    2024-01-20
                  </Descriptions.Item>
                </Descriptions>
              </ProCard>
            </Col>
          </Row>
        </TabPane>
      </Tabs>

      {/* 用户详情模态框 */}
      <Modal
        title="用户详情"
        open={modalVisible}
        onOk={() => setModalVisible(false)}
        onCancel={() => setModalVisible(false)}
        width={600}
      >
        {selectedUser && (
          <ProDescriptions column={1}>
            <ProDescriptions.Item label="用户名">
              {selectedUser.username}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="邮箱">
              {selectedUser.email}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="电话">
              {selectedUser.phone}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="角色">
              <Tag color={getRoleColor(selectedUser.role)}>
                {getRoleText(selectedUser.role)}
              </Tag>
            </ProDescriptions.Item>
            <ProDescriptions.Item label="状态">
              <Tag color={getStatusColor(selectedUser.status)}>
                {getStatusText(selectedUser.status)}
              </Tag>
            </ProDescriptions.Item>
            <ProDescriptions.Item label="部门">
              {selectedUser.department}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="最后登录">
              {selectedUser.lastLogin}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="登录次数">
              {selectedUser.loginCount}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="创建时间">
              {selectedUser.createTime}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="权限">
              {selectedUser.permissions.map((permission) => (
                <Tag key={permission} color="blue">
                  {permission}
                </Tag>
              ))}
            </ProDescriptions.Item>
          </ProDescriptions>
        )}
      </Modal>

      {/* 权限详情模态框 */}
      <Modal
        title="权限详情"
        open={permissionModalVisible}
        onOk={() => setPermissionModalVisible(false)}
        onCancel={() => setPermissionModalVisible(false)}
        width={500}
      >
        {selectedPermission && (
          <ProDescriptions column={1}>
            <ProDescriptions.Item label="权限名称">
              {selectedPermission.name}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="权限代码">
              {selectedPermission.code}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="描述">
              {selectedPermission.description}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="分类">
              {selectedPermission.category}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="状态">
              <Tag
                color={
                  selectedPermission.status === "enabled" ? "green" : "red"
                }
              >
                {selectedPermission.status === "enabled" ? "启用" : "禁用"}
              </Tag>
            </ProDescriptions.Item>
          </ProDescriptions>
        )}
      </Modal>

      {/* 编辑用户抽屉 */}
      <Drawer
        title="编辑用户"
        placement="right"
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        width={400}
      >
        <ProForm
          onFinish={async (values) => {
            message.success("用户信息更新成功！");
            setDrawerVisible(false);
          }}
        >
          <ProFormText
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          />
          <ProFormText
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "请输入正确的邮箱格式" },
            ]}
          />
          <ProFormSelect
            name="role"
            label="角色"
            options={[
              { label: "管理员", value: "admin" },
              { label: "经理", value: "manager" },
              { label: "用户", value: "user" },
              { label: "访客", value: "guest" },
            ]}
            placeholder="请选择角色"
            rules={[{ required: true, message: "请选择角色" }]}
          />
          <ProFormSelect
            name="department"
            label="部门"
            options={[
              { label: "技术部", value: "技术部" },
              { label: "产品部", value: "产品部" },
              { label: "设计部", value: "设计部" },
              { label: "市场部", value: "市场部" },
            ]}
            placeholder="请选择部门"
            rules={[{ required: true, message: "请选择部门" }]}
          />
        </ProForm>
      </Drawer>
    </div>
  );
};

export default Page30;
